<template>
  <a-modal
    class="withdraw-set-modal"
    :visible="visible"
    :title="title"
    :maskClosable="false"
    :destroyOnClose="true"
    :keyboard="false"
    :confirmLoading="confirmLoading"
    width="40%"
    @cancel="closeModal(false)"
    @ok="handleSubmit">

    <a-form-model
      class="withdraw-set-form"
      ref="ruleForm"
      :model="formData"
      :rules="rules"
      :label-col="{ span: 8 }"
      :wrapper-col="{ span: 16 }">
      <a-form-model-item label="提现限制" prop="limitType">
        <a-radio-group :disabled="disabled" v-model="formData.limitType">
          <a-radio :value="1">周期</a-radio>
          <a-radio :value="2">固定日期</a-radio>
        </a-radio-group>
      </a-form-model-item>
      <a-form-model-item label="周期" prop="limitPeriod" v-if="formData.limitType == 1">
        <a-input-number
          allow-clear
          :min="1"
          :precision="0"
          style="width:200px"
          v-model="formData.limitPeriod"
          :disabled="disabled"
          placeholder="请输入周期" />周
      </a-form-model-item>
      <a-form-model-item label="日期" v-if="formData.limitType == 2">
        <a-button v-if="!disabled" type="primary" :disabled="formData.fixedDates.length >= 4" @click="addDates">添加</a-button>
        <input type="hidden" v-model="formData.fixedDates">
        <div v-for="(item, index) in formData.fixedDates" :key="index">
          <a-cascader
            style="width:200px"
            :options="mdArr"
            v-model="item.date"
            :displayRender="({labels, selectedOptions}) => labels.join('-')"
            :disabled="disabled"
            placeholder="请选择日期">
            <a-icon slot="suffixIcon" type="down" />
          </a-cascader>
          <a-button type="link" style="color: red;" :disabled="disabled" @click="delDates(index)">删除</a-button>
        </div>
      </a-form-model-item>
      <a-form-model-item label="提现最低金额" prop="minMoneyNum">
        <a-input-number
          allow-clear
          :min="0"
          :precision="2"
          style="width:200px"
          v-model="formData.minMoneyNum"
          :disabled="disabled"
          placeholder="请输入提现最低金额" />
      </a-form-model-item>
    </a-form-model>

    <template slot="footer">
      <a-button key="back" @click="closeModal(false)"> 取消 </a-button>
      <a-button :loading="confirmLoading" key="submit" type="primary" @click="handleSubmit"> 提交 </a-button>
    </template>
  </a-modal>
</template>

<script>
import deepCopy from '@/utils/deepCopy'
import { mdArr } from './mdArr.js'
const formData = {
  id: '', // 提现设置id
  supplierId: '', // 供应商id
  limitType: 1, // 限制类型
  limitPeriod: 0, // 限制周期
  fixedDate: '', // 限制日期
  fixedDates: [], // 限制日期集合
  minMoneyNum: 0, // 最低提现金额（分）
}
export default {
  name: 'withdrawSet',
  computed: {
    title () { // 弹窗名称
      return `联系人管理：${this.record.supplierName}`
    },
    supplierId () { // 供应商id
      return this.record.id
    }
  },
  props:{
    record: { // 选中供应商信息
      type: Object,
    },
    visible: { // 是否显示弹窗
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      confirmLoading: false, // 提交等待
      formData,
      mdArr,
      disabled: false,
      rules:{ // 表单验证规则
        limitType: [
          { required: true, message: '请选择限制类型', trigger: 'blur' },
        ],
        limitPeriod: [
          { required: true, message: '请输入限制周期', trigger: 'blur' }
        ],
        fixedDates: [
          { required: true, message: '请选择限制日期', trigger: 'change' },
        ],
        minMoneyNum: [
          { required: true, message: '请输入最低提现金额', trigger: 'blur' },
        ],
      }
    };
  },
  watch: {
    // 监听弹窗显示，回显数据
      visible(value) {
        if(value){
          this.getWithdrawSetInfo(this.record.id)
        }
      }
  },
  created() {},
  mounted() {},
  methods: {
    // 重置
    resetData(){
      this.formData=deepCopy(formData);
    },
    // 获取提现设置详情
    async getWithdrawSetInfo(id){
      let res = await this.$get('/withdraw/config/query',
        { supplierId: id });
      if(res && res.returnCode=='1000'){
        if(res.dataInfo){
          res.dataInfo.minMoneyNum = typeof res.dataInfo.minMoney == 'string' ? (Number(res.dataInfo.minMoney)/100).toFixed(2) : (res.dataInfo.minMoney/100).toFixed(2)
          res.dataInfo.fixedDates = []
          if(res.dataInfo.fixedDate) {
            res.dataInfo.fixedDate.split(',').forEach(item => {
              res.dataInfo.fixedDates.push({date: item.split('-')})
            });
          }
          this.formData=deepCopy(res.dataInfo);
        } else {
          this.resetData()
          this.formData.supplierId = id
        }
      }
    },
    // 添加日期
    addDates() {
      if(this.formData.fixedDates.length >= 4) {
        this.$message.warning('最多添加四个固定日期！');
      } else {
        this.formData.fixedDates.push({date: undefined})
      }
    },
    // 删除日期
    delDates(index) {
      this.formData.fixedDates.splice(index, 1)
    },
    // 提交
    handleSubmit() {
      let _this = this
      this.confirmLoading = true;
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          let fixedDate = _this.formData.fixedDates.map((item)=>{
            return item.date.join('-')
          })
          if(_this.formData.limitType == 2 && fixedDate.length == 0) {
            _this.$message.error('请至少选择一个限制日期');
            _this.confirmLoading = false;
            return
          }
          _this.formData.fixedDate = fixedDate.join(',')
          if(_this.formData.minMoneyNum == 0) {
            _this.$message.error('提现最低金额不能为0');
            _this.confirmLoading = false;
            return
          }
          _this.formData.minMoney = Math.round(Number(_this.formData.minMoneyNum) * 10 * 10)
          _this.$post('/withdraw/config/add',
              this.formData)
          .then((res) => {
            _this.confirmLoading = false;
            if (res && res.returnCode == 1000) {
              _this.$message.success('操作成功');
              _this.resetData()
              _this.closeModal(true);
            }
          })
          .catch(err => {
            _this.confirmLoading = false;
          });
        } else {
          _this.confirmLoading = false;
          return false;
        }
      });
    },
    // 关闭弹窗
    closeModal(bool) {
      this.$emit('cancel', bool)
    }
  }
};
</script>

<style lang="less">
  .withdraw-set-form{
    .form-table{
      border: 0;
      th, td{
        border: 0;
      }
    }
  }
</style>
